import { PlusOutlined, EditOutlined, DeleteOutlined, ShoppingOutlined, TransactionOutlined, ProfileTwoTone } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, Divider, Popconfirm, Statistic, Table, message } from 'antd';
import { useRef,useState } from 'react';

import { queryList, addUpdate, memberOp, OperationMemberParams, OperationMemberItem } from '@/services/operation/member';
import MemberForm from './memberForm';
import MemberOpForm from './memberOpForm';
import DetailList from './detailList';

export default () => {
    const [open, setOpen] = useState<boolean>(false);
    const [memberOpVisible, setMemberOpVisible] = useState<boolean>(false);
    const [detailVisible, setDetailVisible] = useState<boolean>(false);
    const [memberId, setMemberId] = useState<Partial<Number> | undefined>();
    const [operationMemberItem, setOperationMemberItem] = useState<Partial<OperationMemberItem> | undefined>();
    const actionRef = useRef<ActionType>();

    /**
     * 添加编辑会员
     * @param fields
    */
    const handleSubmit = async (fields: OperationMemberItem) => {
        setOpen(false);
        setMemberOpVisible(false);
        setDetailVisible(false);

        const msg = fields.id ? '编辑' : '添加';
        message.loading('正在' + msg + '会员');
        const res = await addUpdate({ ...fields });

        if (res.success) {
            message.success(msg + '会员成功');
            if (actionRef.current) {
                actionRef.current.reload();
            }
        } else {
            message.error(res.msg);
        }
    };

    // 操作会员
    const handleOpSubmit = async (fields: OperationMemberItem) => {
      setOpen(false);
      setMemberOpVisible(false);
      setDetailVisible(false);
      
      message.loading('正在操作');
      const res = await memberOp({ ...fields });

      if (res.success) {
          message.success("操成功");
          if (actionRef.current) {
            actionRef.current.reload();
          }
      } else {
          message.error(res.msg);
      }
    };

    const showAddModal = () => {
        setOpen(true);
        setOperationMemberItem({});
    };

    const showEditModal = (item: OperationMemberItem) => {
      setOpen(true);
      setOperationMemberItem(item);
    };

    const showMemberOpForm = (item: OperationMemberItem | undefined) => {
      setMemberOpVisible(true);
      setOperationMemberItem(item);
    };

    /**
     * 查看明细
     * @param item 
     */
    const showDetailForm = (memberId : number) => {
      setDetailVisible(true);
      setMemberId(memberId);
    };

    const columns: ProColumns<OperationMemberItem>[] = [
      {
          title: '手机号',
          dataIndex: 'mobile',
          width: 120
      },
    
      {
          title: '当前余额',
          dataIndex: 'balance',
          hideInSearch: true,
          valueType: 'money'
      },
      {
          title: '总充值',
          dataIndex: 'inAmount',
          hideInSearch: true,
          valueType: 'money'
      },
      {
          title: '总消费',
          dataIndex: 'outAmount',
          hideInSearch: true,
          valueType: 'money'
      },
      {
          title: '姓氏',
          dataIndex: 'firstName',
          hideInSearch: true,
          width: 80
      },
      {
          title: '性别',
          dataIndex: 'gender',
          valueType: 'select',
          width: 60,
          valueEnum: {
            'F': {
              text: '女',
            },
            'M': {
              text: '男',
            },
          },
      },
      {
          title: '名字',
          dataIndex: 'lastName',
          hideInSearch: true,
      },
      {
          title: '年龄',
          dataIndex: 'age',
          hideInSearch: true,
      },
      {
          title: '操作',
          dataIndex: 'option',
          valueType: 'option',
          width: 180,
          render: (_, record) => (
            <>
              <a
                  key="edit"
                  onClick={() => {
                      showEditModal({ ...record})
                  }}
                  title="编辑会员"
              >
                编辑
              </a>
              <Divider type="vertical" />
              <a key="consume"
                onClick={() => {
                  showMemberOpForm({ ...record, opType: 'OUT' });
                }}
                title="会员消费"
              >消费</a>
              <Divider key="credit_refund" type="vertical" />
              <a key="refund"
                onClick={() => {
                  showMemberOpForm({ ...record, opType: 'IN' });
                }}
                title="会员充值"
              >充值</a>
              <Divider key="credit_check" type="vertical" />
              <a
                key="detail"
                onClick={() => {
                  showDetailForm(record.id);
                }}
                title="余额明细"
              >明细</a>
            </>
          ),
        },
    ];

  return (
    <PageContainer title={false}>
        <ProTable<OperationMemberItem>
            rowKey="id"
            actionRef={actionRef}
            columns={columns}
            request={(params) => {
                params.keyword
                return queryList(params as OperationMemberParams);
            }}
            toolBarRender={() => [
              <Button icon={<PlusOutlined />}
                onClick={() => {
                    showAddModal();
                }}
                title="添加会员"
                type="primary">开卡
              </Button>
            ]}
            pagination={{
              pageSize: 10
            }}
            summary={(pageData) => {
              let totalInAmount = 0;
              let totalOutAmount = 0;
              let totalBalance = 0;
      
              pageData.forEach(({ inAmount, outAmount, balance}) => {
                totalInAmount += inAmount;
                totalOutAmount += outAmount;
                totalBalance += balance;
              });
              return (
                <>
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={1}>                                
                      <div style={{fontSize:15}}>合计</div>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={2}>
                      <Statistic value={totalBalance} prefix="￥" precision={2} valueStyle={{fontSize:15, color: '#cf1322'}}/>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={3}>
                      <Statistic value={totalInAmount} prefix="￥" precision={2} valueStyle={{fontSize:15, color: '#3f8600'}}/>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={4}>
                      <Statistic value={totalOutAmount} prefix="￥" precision={2} valueStyle={{fontSize:15, color: '#1677ff'}}/>
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                </>
              );
            }}  
        />
        <MemberForm
          operationMemberItem={operationMemberItem}
          open={open}
          onCancel={() => setOpen(false)}
          onSubmit={handleSubmit}
        />
        <MemberOpForm
          operationMemberItem={operationMemberItem}
          open={memberOpVisible}
          onCancel={() => setMemberOpVisible(false)}
          onSubmit={handleOpSubmit}
        />
        <DetailList
          memberId={memberId as number}
          visible={detailVisible}
          onCancel={() => setDetailVisible(false)}
        />
    </PageContainer>
  );
};